//
//  MWApplicationSearchResultController.m
//  XiRan-iOS
//
//  Created by liuyiming on 2019/11/24.
//  Copyright © 2019 Wood. All rights reserved.
//

#import "MWApplicationSearchResultController.h"
#import "MWApplicationCell.h"
#import "ApplicationInfoViewController.h"

@interface MWApplicationSearchResultController () <UITableViewDataSource, UITableViewDelegate>

@property(nonatomic, strong) UITableView *tableView;
@property(strong, nonatomic) NSMutableArray *resultArray;

@property(nonatomic, strong) NSString *keyword;
@property(nonatomic, assign) NSInteger page;
@property(nonatomic, assign) NSInteger size;
@property(nonatomic, assign) MWRequestMode requestMode;

@end

@implementation MWApplicationSearchResultController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    _page = 1;
    _size = 10;
    _requestMode = MWRequestModeRefresh;
    
    [self setupPageSubviews];
}

- (void)searchWithKeyword:(NSString *)keyword {
    _keyword = keyword;
    [self.resultArray removeAllObjects];
    [self refreshSearch];
}

- (void)clearSearchResult {
    [self.resultArray removeAllObjects];
    [_tableView reloadData];
}

#pragma mark - 刷新数据
- (void)refreshSearch {
    _page = 1;
    _requestMode = MWRequestModeRefresh;
    [self searchWithKeyword:_keyword page:_page size:_size];
}

#pragma mark - 加载更多数据
- (void)loadMoreSearch  {
    _page++;
    _requestMode = MWRequestModeLoadMore;
    [self searchWithKeyword:_keyword page:_page size:_size];
}

#pragma mark - 搜索
- (void)searchWithKeyword:(NSString *)keyword page:(NSInteger)page size:(NSInteger)size {
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    hud.label.text = [[MWConfigManager manager] objectForKey:@"loadin" defaultValue:@"加载中..."];
    NSMutableDictionary *paraDic = [[NSMutableDictionary alloc] init];
    [paraDic setObject:[MWUserManager manager].user.token forKey:@"token"];
    [paraDic setObject:keyword forKey:@"search"];
    [paraDic setObject:[NSString stringWithFormat:@"%ld", (long)page] forKey:@"page"];
    [paraDic setObject:[NSString stringWithFormat:@"%ld", (long)size] forKey:@"size"];
    [paraDic setObject:[MWConfigManager manager].productType forKey:@"is_material"];
    [paraDic setObject:[MWConfigManager manager].language forKey:@"language"];

    MWWeakSelf
    [[MWNetworkManager manager] POST:kApplicationUrl parameters:paraDic progress:^(NSProgress *downloadProgress) {
        
    } success:^(id responseObject) {
        NSDictionary *dic = responseObject;
        NSInteger code = [[dic objectForKey:@"code"] integerValue];
//        NSString *msg = [dic objectForKey:@"msg"];
        if (code == 1) {
            NSArray *tempArray = [MWApplicationModel mj_objectArrayWithKeyValuesArray:[dic objectForKey:@"data"]];
            if (weakSelf.requestMode == MWRequestModeRefresh) {
                [weakSelf.tableView.mj_header endRefreshing];
                [self.resultArray removeAllObjects];
                       
            } else {
                if (tempArray.count < 10) {
                    [weakSelf.tableView.mj_footer endRefreshingWithNoMoreData];
                } else {
                    [weakSelf.tableView.mj_footer endRefreshing];
                }
            }
                   
            [self.resultArray addObjectsFromArray:tempArray];
            [weakSelf.tableView reloadData];
        } else {
            
        }
        [hud hideAnimated:YES];
    } failure:^(NSError *error) {
        NSLog(@"%@", error);
        [hud hideAnimated:YES];
    }];
}

#pragma mark - UITableViewDataSource && UITableViewDelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if ([MWConfigManager manager].isNetError) {
        self.view.hidden = YES;
    } else if (!self.resultArray.count) {
        if (self.isFirst) {
            
        } else {
            self.errorTitleLabel.text = [[MWConfigManager manager] objectForKey:@"nodata" defaultValue:@"暂无数据"];
            self.errorTitleLabel.hidden = self.errorImageView.hidden = NO;
            tableView.hidden = YES;
            self.view.hidden = NO;
        }
    } else {
        self.errorTitleLabel.hidden = self.errorImageView.hidden = YES;
        tableView.hidden = NO;
        self.view.hidden = NO;
    }

    return self.resultArray.count;
}


- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 0.1f;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0.1f;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    return [[UIView alloc] initWithFrame:CGRectZero];
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    return [[UIView alloc] initWithFrame:CGRectZero];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *identifier = @"MWApplicationCell";
    MWApplicationCell *applicationCell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (!applicationCell) {
        applicationCell = [[MWApplicationCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
        applicationCell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    [applicationCell setupData:self.resultArray[indexPath.row]];
    
    return applicationCell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    ApplicationInfoViewController *aic = [[ApplicationInfoViewController alloc] init];
    MWApplicationModel *application = self.resultArray[indexPath.row];
    aic.showroomArray = [NSMutableArray arrayWithArray:application.images];
    aic.navTitleString = application.content;
    [self.navigationController pushViewController:aic animated:YES];
}

#pragma mark - Setter && Getter
- (NSMutableArray *)resultArray {
    if (!_resultArray) {
        _resultArray = [[NSMutableArray alloc] init];
    }
    return _resultArray;
}

#pragma mark - UI
- (void)setupPageSubviews {
    _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
    _tableView.backgroundColor = [UIColor whiteColor];
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _tableView.rowHeight = UITableViewAutomaticDimension;
    _tableView.estimatedRowHeight = 300;
    _tableView.dataSource = self;
    _tableView.delegate = self;
    [self.view addSubview:_tableView];
    
    [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view);
    }];
    
    MJRefreshBackNormalFooter *refreshFooter = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        [self loadMoreSearch];
    }];
    refreshFooter.stateLabel.hidden = YES;
    _tableView.mj_footer.hidden = YES;
    _tableView.mj_footer = refreshFooter;
}


@end
